//@ sourceURL=contractSignManage.js 
CommonUtils.regNamespace("com.im.contractSign");

com.im.contractSign.invoke = function() {
	var param = {
		pageNumber: 1,
	    pageSize: 20
	};
    var client = new com.im.common.ajax();
    var operType = "";
    var contractSign;
    var tmpfiles;//文件上传下载
    var performanceFiles,
    	expectFiles,
    	electronFiles,
    	meetFiles,
    	delFiles,
    	delPerformanceFilesIndex=[],
    	delExpectFilesIndex=[],
    	delElectronFilesIndex=[],
    	delMeetFilesIndex=[];

    function _init() {
        //加载列表信息
    	_initDataList();
    	//重置按钮
    	$('#ResetBtn').click(function (){
    		_resetSearchInfo();
    	});
        //查询按钮
        $("#SearchBtn").click(function(){
        	_loadDataList(true);
        });
        //新增弹出按钮
        $("#addBtn").click(function(){
        	_add();
        });
        //新增编辑保存按钮
        $("#saveBtn").click(function(){
        	_save();
        });
        //批量审定
        $("#batchTrial").click(function(){
            _batchTrial();
        });
        //导出
        $('#export').click(function (){
            _exportList();
        });
        //文件上传菜单切换
        $('.file_menu li').click(function (){
        	$('.file_menu li').removeClass('active');
        	$(this).addClass('active');
        	_choseFile($(this).attr('id'));
        });
//        //所属规划
//        $("#searchPlanProjClass").constantCommpent({
//    	    elmIdSel : "searchPlanProjClass",//需要展示的位置下拉框
//    	    constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
//    	    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
//    	    	_loadDataList(true);
//    	    }
//    	});
//        //承接单位
//        $("#searchOrgName").unitselCommpent({
//            elmIdSel : "searchOrgName",//需要展示的位置下拉框
//            unitType : "30",//单位类型 为空的时候全部查询
//            callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
//            	_loadDataList(true);
//            }
//        });
        //查询条件联动
            $("#searchPlanProjClass").project2unit2itemCommpent({
                elmIdPlanTypeSel : "searchPlanProjClass",
                elmIdUnitSel : "searchOrgName",//组织单位下拉元素
                elmIdItemSel : "searchImpleProjName",//实施项目下拉元素
                orgType : "10",//初始化单位时，单位类型
                callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
                	_loadDataList(true);
                }
            });
        $("#searchPlanProjClassPop").plan2unit2project2itemCommpent({
            elmIdProjectSel : "vAddProjectName",//规划工程下拉元素
            elmIdPlanTypeSel : "searchPlanProjClassPop",//所属规划
            elmIdUnitSel : "orgUnit",//组织单位下拉元素
            elmIdItemSel : "impleProjName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            }
        });

        //时间插件
        $('#startDatepicker,#talkDatepicker,#stepDatepicker,#signDatepicker,#caigouTime').datepicker({
            onSelect:function (){
            	$('#startDatepicker').trigger("change");
            	$('#talkDatepicker').trigger("change");
            	$('#stepDatepicker').trigger("change");
            	$('#signDatepicker').trigger("change");
            	$('#caigouTime').trigger("change");
            }
        });
        //初始化合同类型的值
        _initContractType();
        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();
        //项目内容改变
        $("#impleProjName").bind('change', function () {
            _loadSelect({impleProjId: $("#impleProjName option:selected").attr("value"),contractId:$("#contractId").val()});
        });

        $("#caigou").bind('change', function () {
            if ($("#caigou option:selected").attr("value") != null && $("#caigou option:selected").attr("value") != '') {
                if ($("#caigou option:selected").attr("value") == '60' ) {
                    $("#orgList").removeAttr("disabled");
                    $("#addUnit").removeAttr("disabled");
                    $("#total").removeAttr("disabled");
                } else {
                    $("#orgList").attr("disabled","disabled");
                    $("#addUnit").attr("disabled","disabled");
                    $("#total").attr("disabled","disabled");
                    _loadResultByPurch({purchPlanId: $("#caigou option:selected").attr("value")});
				}
			}
        });

        $("#sortEle").bind('change', function () {
            _loadDataList();
        });

        //验证
        _formValidator();
        //重置验证
        $('#addEditModal').on('hidden.bs.modal', function() {
        	_reset();
        });
        //状态
        var param = {};
        var stateList = null;
        param.tabName = "T_CONTRACT";
        param.colName ="STATUS_CD";
        var result = client.callAsJson("commonService/queryTabColParam", param);
        if (result.success) {
            stateList = result.result;
        } else {
            toastr.error(result.resultMsg);
            return;
        }

        //规划状态列表添加元素
        var statusCds = $("#statusCd");
        $.each(stateList, function (i, item) {
            if(i == 0) {
                statusCds.append("<option value='" + item.colVal + "' selected='selected'>" + item.colValName + "</option>");
            } else {
                statusCds.append("<option value='" + item.colVal + "'>" + item.colValName + "</option>");
            }
        });

        initOrg();

        _initOrgType();

        $("#addUnitBtn").click(function(){
            _saveOrUpdate();
        });

        $("#addUnit").click(function(){
            $('#unitAddModal').modal("show");
        });
    };
    //初始化合同类型
    function _initContractType(){
    	var result = client.callAsJson("commonService/queryBusiConstValByCond",{"constParamCode":"CONTRACT_TYPE"});
    	if(result.resultCode=='0'){
    	    $.each(result.result, function (i,item) {
      	      $('#contractType').append("<option value=" + item.paramValValue + ">" +item.paramValName + "</option>");
      	    });
      	    $('.select2').select2();
    	}else{
    	    toastr.error(result.resultMsg);
    	}
    }
    //选择项目后回填采购计划与中标通知书
    function _loadSelect(param){
    	  $('#caigou').empty();
    	  $('#noticeCode').empty();
    	  var isCaigou = false;
    	 // var result = client.callAsJson("contractService/queryNoticeAndPurchasePlanByProjectId",param);
          var result = client.callAsJson("purchaseService/queryPurchasePlanByParam",param);

          if (result.resultCode=='0') {
              $('#caigou').append("<option value='60'>自由采购</option>");
              $.each( result.result, function (i) {
                  isCaigou = true;
                  $('#caigou').append("<option value=" + result.result[i].purchPlanId + ">" +"【"+result.result[i].purchPlanNum+"】"+result.result[i].purchPlanName + "</option>");
              });
              // if (isCaigou) {
              //     $("#orgList").attr("disabled","disabled");
              //     $("#addUnit").attr("disabled","disabled");
              //     $("#total").attr("disabled","disabled");
              // } else {
              //     $("#orgList").removeAttr("disabled");
              //     $("#addUnit").removeAttr("disabled");
              //     $("#total").removeAttr("disabled");
              // }
		  } else {
              $('#caigou').append("<option value='60'>自由采购</option>");
		  }



    	  // if(result.resultCode=='0'){
    		// if(result.result.purchmap){  ///有采购计划
    		// 	$.each(result.result.purchmap, function(key, value) {
           //          isCaigou = true;
    	  //              $("#caigou").append($("<option/>").text(value).attr("value",key));
    	  //            });
         	//     $("#caigou").val(result.result.purchPlanName).trigger("change");
              //   if (isCaigou) {
              //       $("#orgList").attr("disabled","disabled");
              //       $("#addUnit").attr("disabled","disabled");
              //       $("#total").attr("disabled","disabled");
				// } else {
              //       $("#orgList").removeAttr("disabled");
              //       $("#addUnit").removeAttr("disabled");
              //       $("#total").removeAttr("disabled");
				// }
          //
    		// } else {   //无采购计划
           //      $("#orgList").removeAttr("disabled");
           //      $("#addUnit").removeAttr("disabled");
           //      $("#total").removeAttr("disabled");
			// }
    		// if(result.result.noticeName != ""){
	     	//     $('#noticeCode').append("<option>" +result.result.noticeName + "</option>");
	     	//     $("#noticeCode").val(result.result.noticeName).trigger("change");
           //      $('#total').val(result.result.budgetAmount).trigger("change");
           //      $('#resultId').val(result.result.resultId);
    		// }else {
           //      $('#total').removeAttr("disabled");
           //      $("#noticeCode").val("");
           //      $('#total').val("");
           //      $('#resultId').val("");
           //  }
     	 //    //$('#contractCode').val(result.result.contractCode);
    	  // }else{
      	//     //toastr.error(result.resultMsg);
    	  // }
    }

    //选择采购计划后后回填采购计划与中标通知书
    function _loadResultByPurch(param){
        $('#noticeCode').empty();
        var result = client.callAsJson("contractService/queryNoticeByPurchPlanId",param);
        if(result.resultCode=='0'){
        	$("#planType").val(result.result.planType);
        	if (result.result.noticeName != undefined) {
                $('#noticeCode').append("<option>" +result.result.noticeName + "</option>");
                $("#noticeCode").val(result.result.noticeName).trigger("change");
                $('#total').val(result.result.budgetAmount).trigger("change");
                $('#resultId').val(result.result.resultId);
                if ($('#caigouPerson').val() == "") {
                    $('#caigouPerson').val(result.result.linkMan);
				}
			} else {
                $('#noticeCode').empty();
                $('#resultId').empty();
                $('#total').val("");
                $('#caigouPerson').val("");

			}

        }else{
            //toastr.error(result.resultMsg);
        }
    }
    //重置搜索条件
    function _resetSearchInfo(){
    	$('#searchOrgName').val("").trigger("change");
    	$('#searchPlanProjClass').val("").trigger("change");
    	$('#searchImpleProjName').val("").trigger("change");
    }
    //更新数据列表
    function _loadDataList(pageNumber){
    	param.pageNumber = 1;
    	var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	var impleProjName = impleProjId == '' ? '' : $("#searchImpleProjName option:selected").html();
    	var orgId = $("#searchOrgName option:selected").attr("value");
    	var orgName = orgId == '' ? '' : $("#searchOrgName option:selected").html();
    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
        param.impleProjName = impleProjName;
        param.orgName = orgName;
        param.orgId = orgId;
        param.planProjClass = planProjClass;
        param.sortEle =$("#sortEle option:selected").attr("value");
        if(pageNumber){
    		param.pageNumber = 1;
            $('#contractSignList').datagrid("load",param);
        }else{
    	   $('#contractSignList').datagrid("reload",param);
        }
    }

    //新增编辑(保存按钮)
    function _save(){
    	$("#contractSignForm").data("bootstrapValidator").validate();
    	var flag = $("#contractSignForm").data("bootstrapValidator").isValid();
    	if($("#total").val() == "" || !/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,4})?$/.test($("#total").val())) {
            toastr.error("请填写不超过4位小数的中标金额");
            return;
		}
    	if(flag){
	    	var saveparam={};
	    	if($("#contractId").val() != ''){
	    		saveparam.contractId= $("#contractId").val();
	    	}
	    	//文件类型区分
	    	var filename = $('#common_file_name label');
	    	var files0 = [];
	    	var files1 = [];
	    	var files2 = [];
	    	var files3 = [];
	    	for(var i = 0;i<filename.length;i++){
	    		if(filename.eq(i).hasClass('0')){
	    			files0.push(filename.eq(i).html());
	    		}else if(filename.eq(i).hasClass('1')){
	    			files1.push(filename.eq(i).html());
	    		}else if(filename.eq(i).hasClass('2')){
	    			files2.push(filename.eq(i).html());
	    		}else if(filename.eq(i).hasClass('3')){
	    			files2.push(filename.eq(i).html());
	    		}
	    	}
	    	saveparam.contractName= $("#contractName").val();
	    	saveparam.contractCode= $("#contractCode").val();
	    	//saveparam.contractId  =$("#contractId").val();
	    	saveparam.contractType= $("#contractType  option:selected").attr('value');
	    	//saveparam.description= $("#description").val();
	    	saveparam.impleProjId= $("#impleProjName  option:selected").attr('value');
	    	saveparam.noticeName= $("#noticeCode").val();
	    	saveparam.purchaseMan= $("#caigouPerson").val();
	    	saveparam.purchaseDesc= $("#caigouTime").val();
            if ($("#caigou").val() == '0') {
                saveparam.planType = $("#caigou").val();
			} else {
                saveparam.purchPlanId= $("#caigou").val();
                saveparam.planType = $("#planType").val();
			}
	    	saveparam.imprestInfo= $("#imprestInfo").val();
	    	saveparam.contractTakeDt= $("#talkDatepicker").val();
	    	saveparam.contractEndDt= $("#stepDatepicker").val();
	    	saveparam.contractSignDt= $("#signDatepicker").val();
	    	saveparam.performanceInfo= $("#performanceInfo").val();
	    	saveparam.purchaseDesc= $("#caigouTime").val();
	    	saveparam.startDt= $("#startDatepicker").val();
	    	saveparam.total= $("#total").val();
	    	saveparam.contractClauseName= $("#contractClauseName").val();
	    	saveparam.resultId= $("#resultId").val();
            saveparam.statusCd= $("#statusCd").val();
            saveparam.orgId =$("#orgList  option:selected").attr('value');
	    	saveparam.performanceFiles = [];
	    	saveparam.expectFiles = [];
            saveparam.electronFiles = [];
            saveparam.meetFiles = [];
	    	if(filename.length >0){
		    	client.callAsFile(tmpfiles.newly, function(result) {
	                if(!result.success){
	                	toastr.error('文件上传失败！');
	                	return false;
	                }else{
	                	var performanceFilesNow = [];
	                	var expectFilesNow = [];
	                	var electronFilesNow = [];
	                	var meetFilesNow = [];
	                	$.each(result.result,function (index,item){
                    		if($.inArray(item.attachFullName,files0) !=-1){
                    			performanceFilesNow.push(item);
                    		}else if($.inArray(item.attachFullName,files1) !=-1){
                    			expectFilesNow.push(item);
                    		}else if($.inArray(item.attachFullName,files2) !=-1){
                    			electronFilesNow.push(item);
                    		}else if($.inArray(item.attachFullName,files3) !=-1){
                    			meetFilesNow.push(item);
                    		}
                    	});
	                	saveparam.performanceFiles= performanceFilesNow;
	                	saveparam.expectFiles= expectFilesNow;
	                	saveparam.electronFiles= electronFilesNow;
	                	saveparam.meetFiles= meetFilesNow;
	                	toastr.success('文件上传成功！');
	                	//添加上已经存在的文件/删除的文件
	            		saveparam.delFiles = delFiles;
	            		$.each(performanceFiles,function(index,item){
	            			if($.inArray(index,delPerformanceFilesIndex) ==-1){
	            				(saveparam.performanceFiles).push(item);
	            			}
	            		});
	            		$.each(expectFiles,function(index,item){
	        				if($.inArray(index,delExpectFilesIndex) ==-1){
	        					(saveparam.expectFiles).push(item);
	        				}
	        			});
	            		$.each(electronFiles,function(index,item){
	        				if($.inArray(index,delElectronFilesIndex) ==-1){
	        					(saveparam.electronFiles).push(item);
	        				}
	        			});
	            		$.each(meetFiles,function(index,item){
	        				if($.inArray(index,delMeetFilesIndex) ==-1){
	        					(saveparam.meetFiles).push(item);
	        				}
	        			});
	        	        var result = client.callAsJson("contractService/saveOrUpdateContract", saveparam);
	        	        if(result.resultCode=='0'){
	        	        	$("#addEditModal").modal("hide");
	                    	toastr.success('保存成功！');
	        	    		_loadDataList();
	        	    	}else {
	        	            toastr.error(result.result.message);
	        	        }
	               }
	            });
	    	}else{
	    		//添加上已经存在的文件/删除的文件
	    		saveparam.delFiles = delFiles;
	    		$.each(performanceFiles,function(index,item){
	    			if($.inArray(index,delPerformanceFilesIndex) ==-1){
	    				(saveparam.performanceFiles).push(item);
	    			}
	    		});
	    		$.each(expectFiles,function(index,item){
					if($.inArray(index,delExpectFilesIndex) ==-1){
						(saveparam.expectFiles).push(item);
					}
				});
        		$.each(electronFiles,function(index,item){
    				if($.inArray(index,delElectronFilesIndex) ==-1){
    					(saveparam.electronFiles).push(item);
    				}
    			});
        		$.each(meetFiles,function(index,item){
    				if($.inArray(index,delMeetFilesIndex) ==-1){
    					(saveparam.meetFiles).push(item);
    				}
    			});
		        var result = client.callAsJson("contractService/saveOrUpdateContract", saveparam);
		        if(result.resultCode=='0'){
		        	$("#addEditModal").modal("hide");
	            	toastr.success('保存成功！');
		    		_loadDataList();
		    	}else {
		            toastr.error(result.result.message);
		        }
	    	}
    	}
    }
    //验证
    function _formValidator(){
    	$("#contractSignForm").bootstrapValidator({
    	    feedbackIcons: {
    	      valid: 'glyphicon glyphicon-ok',
    	      invalid: 'glyphicon glyphicon-remove',
    	      validating: 'glyphicon glyphicon-loadData'
    	    },
    	    excluded: [':hidden', ':not(:visible)'],
    	    fields: {
    	    	contractName:{
    	    		validators: {
  	    	          notEmpty: {
  	    	            message: '合同名称不能为空'
  	    	          }
  	    	        }
    	    	},
    	    	contractType: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '合同类型不能为空'
	    	          }
	    	        }
    	    	},
				/*
    	    	orgUnit: {
    	            trigger:"change",
	    	        validators: {
	    	          notEmpty: {
	    	            message: '请选择建设单位'
	    	          }
	    	        }
    	    	},
    	    	*/
    	    	impleProjName: {
    	            trigger:"change",
	    	        validators: {
	    	          notEmpty: {
	    	            message: '请选择实施项目'
	    	          }
	    	        }
    	    	},
				/*
    	    	caigou: {
    	            trigger:"change",
	    	        validators: {
	    	          notEmpty: {
	    	            message: '请选择采购计划'
	    	          }
	    	        }
    	    	},*/
    	    	caigouPerson: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '采购经手人不能为空'
	    	          }
	    	        }
    	    	},
    	    	getDt: {
    	            trigger:"change",
	    	        validators: {
	    	          notEmpty: {
	    	            message: '请选择归档时间'
	    	          }
	    	        }
    	    	},
//    	    	noticeCode: {
//    	            trigger:"change",
//	    	        validators: {
//	    	          notEmpty: {
//	    	            message: '中标通知书不能为空'
//	    	          }
//	    	        }
//    	    	},
//    	    	total: {
//    	            trigger:"change",
//	    	        validators: {
//	    	          notEmpty: {
//	    	            message: '总金额不能为空'
//	    	          },
//	    	          regexp: {
//                          regexp: /^\d+(\.\d+)?$/,
//                          message: '总金额只能包含数字/小数点'
//                      }
//	    	        }
//    	    	},
//     	    	talkDt: {
//     	            trigger:"change",
// 	    	        validators: {
// 	    	          notEmpty: {
// 	    	            message: '请选择合同谈判时间'
// 	    	          }
// 	    	        }
//     	    	},
//     	    	comptentDt: {
//     	            trigger:"change",
// 	    	        validators: {
// 	    	          notEmpty: {
// 	    	            message: '请选择合同流程完成时间'
// 	    	          }
// 	    	        }
//     	    	},
//     	    	signDt: {
//     	            trigger:"change",
// 	    	        validators: {
// 	    	          notEmpty: {
// 	    	            message: '请选择合同签订时间'
// 	    	          }
// 	    	        }
//     	    	},
//    	    	startDt: {
//    	            trigger:"change",
//	    	        validators: {
//	    	          notEmpty: {
//	    	            message: '开工时间不能为空'
//	    	          }
//	    	        }
//    	    	},
    	    	contractClauseName: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '支付条款不能为空'
	    	          }
	    	        }
    	    	}
    	    }
    	  });
    }
    //重置验证
    function _reset(){
    	$("#contractSignForm").data('bootstrapValidator').destroy();
        $('#contractSignForm').data('bootstrapValidator', null);
        _formValidator();
    }
    //新增操作
    function _add(index){
    	 $("#addEditModal .modal-title").html("合同签订增加");
    	 _show();
         $("#addEditModal").modal("show");
    }
    //删除操作
    function _delete(index){
    	com.im.common.confirm("确定要删除吗？", null, function () {
    	  contractSign = $('#contractSignList').datagrid('getData').rows[index];
    	  var result = client.callAsJson("contractService/deleteContract", {'contractId':contractSign.contractId});
    	  if (result.resultCode=="0") {
    		  _loadDataList();
		      toastr.success("删除成功");
          } else {
              toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
          }
    	});
    }
    //编辑操作
    function _edit(index){
    	 $("#addEditModal .modal-title").html("合同签订修改");
    	 contractSign = $('#contractSignList').datagrid('getData').rows[index];
    	  var result = client.callAsJson("contractService/queryContractdetail", {'contractId':contractSign.contractId});
    	  if (result.resultCode=="0") {
              if(result.result!= null){
            	  _show(result.result);
              }
          } else {
              toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
          }
         $("#addEditModal").modal("show");
    }
    //选择文件
    function _choseFile(type){
    	var filename = $('#common_file_name label');
    	for(var i = 0;i<filename.length;i++){
    		if(filename.eq(i).hasClass(type)){
    			filename.eq(i).show();
    			$('#common_file_name a').eq(i).show();
    			$('#common_file_name br').eq(i).show();
    		}else{
    			filename.eq(i).hide();
    			$('#common_file_name a').eq(i).hide();
    			$('#common_file_name br').eq(i).hide();
    		}
    	}
    }
    //新增编辑模态框数据初始化
    function _show(contractSign){
        $('#total').val("");
        $('#resultId').val("");
        $("#orgList").val("");
    	if(contractSign==null){  //增加
            $('#total').removeAttr("disabled");
            $("#orgList").removeAttr("disabled");
            $("#addUnit").removeAttr("disabled");
            //文件
            var file = new com.im.common.file();
            tmpfiles = file.activate(1);
            $('#common_file').val('');
            $('#common_file_name').hide();
//    		var result = client.callAsJson("commonService/getSeqForRule", {'seqType':'4','seqArg':'HNJTT-XM-20180526000021'});
    		 $("#contractCode").val("");
             $("#contractName").val("");
             $("#contractId").val("");
             $("#imprestInfo").val("");
             $("#performanceInfo").val("");
             $("#purchaseDesc").val("");
             $("#contractType").val("").trigger("change");
             $("#impleProjName").val("").trigger("change");
             $("#orgUnit").val("42bdd723-c20a-47a2-a399-cbf6d2255bdc").trigger("change");//默认厅科技信息中心
             $("#statusCd").val("10").trigger("change");
//             $("#impleProjName").attr('projectid',"");
//             $("#impleProjId").val("");
	         $("#talkDatepicker").val("");
	         $("#stepDatepicker").val("");
	         $("#signDatepicker").val("");
             $('#caigou').empty();
	         $("#caigouPerson").val("");
       	     $('#noticeCode').empty();
             $("#total").val("");
             $("#caigouTime").val("");
             $("#resultId").val("");
             $("#startDatepicker").val("");
             $("#contractClauseName").val("");
             //$("#description").val("");
	         $('#hasFiles').hide();
	         $('#performanceFiles dd').remove();
	         $('#expectFiles dd').remove();
             $('#electronFiles dd').remove();
             $('#meetFiles dd').remove();
	         delFiles = [];
	         performanceFiles = [];
	         expectFiles = [];
             electronFiles = [];
             meetFiles = [];
            if ($("#searchPlanProjClass option:selected").attr("value") != null && $("#searchPlanProjClass option:selected").attr("value") != '') {
                $("#searchPlanProjClassPop").val($("#searchPlanProjClass option:selected").attr("value")).trigger("change");
            }
            if ($("#searchOrgName option:selected").attr("value") != null && $("#searchOrgName option:selected").attr("value") != '') {
                $("#orgUnit").val($("#searchOrgName option:selected").attr("value")).trigger("change");
            }

            if ($("#searchImpleProjName option:selected").attr("value") != null && $("#searchImpleProjName option:selected").attr("value") != '') {
                $("#impleProjName").val($("#searchImpleProjName option:selected").attr("value")).trigger("change");
            }
    	}else{
			//文件
            $('#total').attr("disabled","disabled");
            $('#total').val(contractSign.total);
            var file = new com.im.common.file();
            tmpfiles = file.activate(1);
            $('#common_file').val('');
            $('#common_file_name').hide();
            $("#orgUnit").val(contractSign.orgId).trigger("change");
	   		 $("#contractCode").val(contractSign.contractCode);
	         $("#contractName").val(contractSign.contractName);
	         $("#contractId").val(contractSign.contractId);
	         $("#imprestInfo").val(contractSign.imprestInfo);
	         $("#performanceInfo").val(contractSign.performanceInfo);
	         $("#purchaseDesc").val(contractSign.purchaseDesc);
	         $("#contractType").val(contractSign.contractType).trigger("change");
             $("#searchPlanProjClassPop").val(contractSign.planProjClass).trigger("change");
             $("#vAddProjectName").val(contractSign.planProjId).trigger("change");
             $("#impleProjName").val(contractSign.impleProjId).trigger("change");
             $("#caigou").val(contractSign.purchPlanId).trigger("change");

//             $("#impleProjName").attr('projectid',contractSign.impleProjId);
//	         $("#impleProjId").val(contractSign.impleProjId);
	        // _loadSelect({impleProjId: contractSign.impleProjId,contractId: contractSign.contractId});//根据合同id查询采购计划/中标通知书/金额
	         $("#startDatepicker").val(contractSign.startDt);
	         $("#talkDatepicker").val(contractSign.contractTakeDt);
	         $("#stepDatepicker").val(contractSign.contractEndDt);
	         $("#signDatepicker").val(contractSign.contractSignDt);
	         $("#caigouTime").val(contractSign.purchaseDesc);
	         $("#caigou").val(contractSign.purchPlanId);
	         $("#caigouPerson").val(contractSign.purchaseMan);
	         $("#contractClauseName").val(contractSign.contractClauseName);
            $("#statusCd").val(contractSign.status).trigger("change");
            $("#orgList").val(contractSign.taskOrgId).trigger("change");
	         //$("#description").val(contractSign.description);
	         //展示已存在文件
	         $('#hasFiles').show();
	         $('#performanceFiles dd').remove();
	         $('#expectFiles dd').remove();
	         $('#electronFiles dd').remove();
	         $('#meetFiles dd').remove();
	         delFiles = contractSign.delFiles;
	         performanceFiles = contractSign.performanceFiles;
	         expectFiles = contractSign.expectFiles;
	         electronFiles = contractSign.electronFiles;
	         meetFiles = contractSign.meetFiles;
	         $.each(contractSign.performanceFiles,function (index,item){
	        	 var dd = '<dd>'+item.attachFullName+'<a href="javascript:;" onclick="com.im.contractSign.invoke.delFiles(this,'+index+',0);">删除</a></dd>';
	        	 $('#performanceFiles').append(dd);
	         });
	         $.each(contractSign.expectFiles,function (index,item){
	        	 var dd = '<dd>'+item.attachFullName+'<a href="javascript:;" onclick="com.im.contractSign.invoke.delFiles(this,'+index+',1);">删除</a></dd>';
	        	 $('#expectFiles').append(dd);
	         });
	         $.each(contractSign.electronFiles,function (index,item){
	        	 var dd = '<dd>'+item.attachFullName+'<a href="javascript:;" onclick="com.im.contractSign.invoke.delFiles(this,'+index+',2);">删除</a></dd>';
	        	 $('#electronFiles').append(dd);
	         });
	         $.each(contractSign.meetFiles,function (index,item){
	        	 var dd = '<dd>'+item.attachFullName+'<a href="javascript:;" onclick="com.im.contractSign.invoke.delFiles(this,'+index+',3);">删除</a></dd>';
	        	 $('#meetFiles').append(dd);
	         });
    	}
    	//文件上传
    	$('#common_file').change(function (){
    		$('#common_file_name label:last').addClass($('.file_menu li.active').attr('id'));
    	});
    }
    //删除已存在文件
    function _delFiles(obj,index,type){
    	if(type == 0){
    		delFiles.push(performanceFiles[index]);
    		delPerformanceFilesIndex.push(index);
    	}else if(type == 1){
    		delFiles.push(expectFiles[index]);
    		delExpectFilesIndex.push(index);
    	}else if(type == 2){
    		delFiles.push(electronFiles[index]);
    		delElectronFilesIndex.push(index);
    	}else if(type == 3){
    		delFiles.push(meetFiles[index]);
    		delMeetFilesIndex.push(index);
    	}
    	$(obj).parents('dd').hide();
    }
    //初始化表格数据
    function _initDataList(){
    	var columns=[[
            {field:'全选',title:"全选",checkbox:true,width:20,fitColumns:true},
    	    {field:'序号',title:"序号",resizable:true,
    	              	formatter: function(value,row,index){
							  if(row.contractId == null) {
								return  "";
							  } else {
                                  return  index+1;
							  }
    	                  }
    	    },
    	    {field:'impleProjName',title:"项目名称",width:130,resizable:true,align:'left'},
            //{field:'contractCode',title:"合同编号",width:75,resizable:true,align:'center'},
            {field:'contractName',title:"合同名称",width:150,resizable:true,align:'left',
                formatter: function(value,row,index){

                    if(row.electronFiles!=null && row.electronFiles.length>0){
                        var html="";
                        for(var i=0;i<row.electronFiles.length;i++){
                            html+="<span style='cursor:pointer'><u><a onclick='downloadFile(\""+row.electronFiles[i].attachPath+"\",\""+row.electronFiles[i].attachFullName+"\")'>【"+row.contractCode+"】"+ row.contractName+"</a></u></span><br>";
                        }
                        return html;
                    }else{
                        return row.contractName;
                    }
                }
			},

            {field:'purchPlanNum',title:"采购计划号",width:90,resizable:true,align:'left'},
            {field:'prepayTotal',title:"预算金额",width:75,resizable:true,align:'center',
                formatter: function(value,row,index){
                    if(value == "") {
                        return "0";
                    }else {
                        return value;
                    }
                }},
    	    {field:'purchPlanTypeName',title:"招标方式",width:85,resizable:true,align:'center',
                formatter: function(value,row,index){
                        return value;
                }},
            // {field:'openDt',title:"招标日期",width:75,resizable:true,align:'center'},
            // {field:'issueDt',title:"中标通知<br>发放日期",width:75,resizable:true,align:'center'},
            {field:'openDt',title:"标书日期",width:150,resizable:true,align:'center',
                formatter: function(value,row,index){
                    if(row.contractId == null) {
                        return  "";
                    } else {
                        return "<b>招标日期:</b>"+row.openDt+"<br><b>通知发放日期:</b>"+row.issueDt;
					}
                }},
    	    {field:'money',title:"合同金额<br>(万元)",width:75,resizable:true,align:'center'},
            {field:'contractTakeDt',title:"合同日期",width:150,resizable:true,align:'center',
                formatter: function(value,row,index){
                    if(row.contractId == null) {
                        return  "";
                    } else {return  "<b>谈判日期:</b>"+row.contractTakeDt
						+"<br><b>流程完成日期:</b>"+row.contractEndDt
                        +"<br><b>签订日期:</b>"+row.contractSignDt;
                    }
                }},
            // {field:'contractTakeDt',title:"合同谈判<br>日期",width:75,resizable:true,align:'center'},
            // {field:'contractSignDt',title:"合同签订<br>日期",width:75,resizable:true,align:'center'},
            // {field:'contractEndDt',title:"合同流程<br>完成日期",width:75,resizable:true,align:'center'},

            {field:'purchaseMan',title:"采购经手人",width:80,resizable:true,align:'center'},
            {field:'taskOrgName',title:"受托单位",width:80,resizable:true,align:'center'},

        	{field:'performanceFiles',title:"履约保函",width:100,resizable:true,align:'left',
    	        formatter: function(value,row,index){
    	        	var files = '';
    	        	$.each(value,function (index,item){
    	        		files += '<br/>'+ item.attachFullName;
    	        	});
    	        	return files;
    	    }},
        	{field:'expectFiles',title:"预付款保函",width:100,resizable:true,align:'left',
    	        formatter: function(value,row,index){
    	        	var files = '';
    	        	$.each(value,function (index,item){
    	        		files += '<br/>'+ item.attachFullName;
    	        	});
    	        	return files;
    	    }},
            // {field:'electronFiles',title:"电子合同",width:90,resizable:true,align:'center',
            //     formatter: function(value,row,index){
            //         var files = '';
            //         $.each(value,function (index,item){
            //             files += '<br/>'+ item.attachFullName;
            //         });
            //         return files;
            //     }},

            {field:'contractClauseName',title:"支付条款",width:290,fitColumns:true,resizable:true,align:'left',formatter: function(value,row,index){
                 if(value){
                    if(value.length > 120){
                      	return "<span style='cursor:pointer'><a onclick='com.im.contractSign.invoke.showSubjectContent(\""+row.contractName+"\",\""+ value +"\")'>" + value.substr(0,65) + "...</a></span>";
                    }else{
                        // return "<a href='javascript:;' data-toggle='modal' onclick='com.im.contractSign.invoke.showSubjectContent("+ index +")'>" + value + "</a>";
                        return "<span style='cursor:pointer'><a onclick='com.im.contractSign.invoke.showSubjectContent(\""+row.contractName+"\",\""+ value +"\")'>" + value + "</a></span>";
                    }
                }
            }
            },

        	{field:'status',title:"状态",resizable:true,align:'center'},
    	    {field:'operation',title:"操作",align:'center',
    	        formatter: function(value,row,index){
                    if(row.contractId == null) {
                        return  "";
                    }else if(row.status==10){
    	        		   return  '<a href="javascript:; "onclick="com.im.contractSign.invoke.editList(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a> '+
   	                    '<a href="javascript:; "onclick="com.im.contractSign.invoke.deleteList(\''+index+'\')" title="删除"><i class="fa fa-trash"></i></a>';
    	        	}else{
    	        		   return  '<a href="javascript:; "onclick="com.im.contractSign.invoke.editList(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a>';
    	        	}
    	    }},
    	]];
    	$('#contractSignList').datagrid({
    	    url:'/InfoManageWeb/contractService/queryContractList',
    	    method:'post',
    	    dataType : 'json',
    	    height:600,
    	    queryParams:param,
    	    pagination:true,
    	    nowrap:false,
//    	    fitColumns:true,
    	    columns:columns,
            showFooter:true,
            loadMsg:'数据加载中，请耐心等待',
    	    onBeforeLoad : function(param){
	    	    for (var key in param) {
		    	    if(key=="rows"){
		    	    	delete param[key];
		    	    }
		    	}
    	    },
    	    loadFilter:function(data){
    	      if(data.resultCode!=0){
    	        toastr.error(data.resultCode);
    	        return null;
    	      }else{
    	        return data.result;
    	      }
    	    },
    	});
    	var p = $('#contractSignList').datagrid('getPager');
    	  $(p).pagination({
    	    pageSize: 20,
    	    pageList: [10,20,30],
    	    beforePageText: '第',
    	    afterPageText: '页    共 {pages}  页',
    	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    	    onSelectPage:function(pageNumber, pageSize){
    	      param.pageNumber=pageNumber;
    	      param.pageSize=pageSize;
    	    	var impleProjId = $("#searchImpleProjName option:selected").attr("value");
    	    	var impleProjName = impleProjId == '' ? '' : $("#searchImpleProjName option:selected").html();
    	    	var orgId = $("#searchOrgName option:selected").attr("value");
    	    	var orgName = orgId == '' ? '' : $("#searchOrgName option:selected").html();
    	    	var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
    	        param.impleProjName = impleProjName;
    	        param.orgName = orgName;
    	        param.orgId = orgId;
    	        param.planProjClass = planProjClass;
    	        param.sortEle ='contractCode';
    	      $('#contractSignList').datagrid('reload',param);
    	    }
    	  });
    }

    //导出表格
    function _exportList(){
        var param = {
            "classes": "ContractService",
            "fileName": "合同签订列表",
            "method": "queryContractList",
            "title": {
                "impleProjName":"项目名称",
               // "contractCode":"合同编号",
                "contractName": "合同名称",
                "purchPlanTypeName": "招标方式",
                "purchPlanNum": "采购计划号",
                "prepayTotal": "预算金额",
                "money": "合同金额（万元）",
                "openDt": "招标日期",
                "contractSignDt": "合同签订日期",
                "contractTakeDt": "合同谈判日期",
                "contractEndDt": "合同流程完成日期",
                "issueDt": "中标通知发放日期",
                "purchaseMan": "采购经手人",
                "orgName": "受托单位",
                "performanceFiles": "履约保函",
                "expectFiles": "预付款保函",
                "electronFiles": "电子合同",
                "contractClauseName": "支付条款",
                "status": "状态"
            }
        };
        var impleProjId = $("#searchImpleProjName option:selected").attr("value");
        var impleProjName = impleProjId == '' ? '' : $("#searchImpleProjName option:selected").html();
        var orgId = $("#searchOrgName option:selected").attr("value");
        var orgName = orgId == '' ? '' : $("#searchOrgName option:selected").html();
        var planProjClass = $("#searchPlanProjClass option:selected").attr("value");
        param.param={};
        param.param.impleProjName = impleProjName;
        param.param.orgName = orgName;
        param.param.orgId = orgId;
        param.param.planProjClass = planProjClass;
        var url='/InfoManageWeb/commonService/export?json='+encodeURI(JSON.stringify(param));
        window.open(url, '_blank');
    }

    function _batchTrial() {
        if($('#contractSignList').datagrid('getChecked').length == 0) {
            com.im.common.confirm("请选择项目", null, function () {
                return;
            });
        } else {
            var contractIds = "";
            $.each($('#contractSignList').datagrid('getChecked'), function(index, item){
                if(item.contractId != null){
                    contractIds += item.contractId + ",";
                }
            });

            var saveparam={};
            saveparam.contractIds = contractIds;
            saveparam.statusCd = 20;
            var client = new com.im.common.ajax();
            var result = client.callAsJson("contractService/updateBatchContract", saveparam);
            if(result.result.resultCode == '0'){
                toastr.success("批量审定成功！");
                _loadDataList();
            }else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        }
    }

    /**
     * 支付条款
     * @param object
     * @private
     */
    function _showSubjectContent(contractName,contractClause) {
         $("#vContractClauseDetailName").text("【"+contractName+"】支付条款");
         $("#vContractClauseDetailNameContent").html(contractClause);
         $("#contractClauseDetail").modal("show");
    }

	return {
		init : _init,
		deleteList : _delete,
		editList : _edit,
		delFiles: _delFiles,
        showSubjectContent:_showSubjectContent
	}
}();

function initOrg(){
    $("#orgList").empty();
    var client = new com.im.common.ajax();
    var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","notOrgType":10});

    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        console.log(result);
        result.result.unshift({'orgId':'','orgName':'请选择'});
        $.each( result.result, function (i) {
            $('#orgList').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

        });
        $("#orgList").select2({});
        $("#orgList").select2().trigger("change");
    }
}

function _saveOrUpdate(){
    var client = new com.im.common.ajax();
    $("#unitForm").bootstrapValidator('validate');//提交验证
    if (!$("#unitForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
        return;
    }

    var orgName =  $("#orgNameInput").val();
    if(orgName == undefined || orgName == ''){
        toastr.warning("请填写单位名称！！");
        return;
    }
    var orgType =  $("#orgTypeSel").val();
    if(orgType == undefined || orgType == ''){
        toastr.warning("请选择单位类型！！");
        return;
    }
    var orgAddr = $("#orgAddrInput").val();
    // if(orgAddr == undefined || orgAddr == ''){
    //     toastr.warning("请填写单位地址！！");
    //     return;
    // }
    var orgTel = $("#orgTelInput").val();
    // if(orgTel == undefined || orgTel == ''){
    //     toastr.warning("请单位联系方式！！");
    //     return;
    // }
    var orgFax =  $("#orgFaxInput").val();
    var orgEmail =  $("#orgEmailInput").val();

    var linkMan = $("#linkManInput").val();
    // if(linkMan == undefined || linkMan == ''){
    //     toastr.warning("请填写单位联系人！！");
    //     return;
    // }
    var linkManTel =  $("#linkManTelInput").val();
    // if(linkManTel == undefined || linkManTel == ''){
    //     toastr.warning("请填写单位联系人电话！！");
    //     return;
    // }
    var linkManPhone = $("#linkManPhoneInput").val();
    // if(linkManPhone == undefined || linkManPhone == ''){
    //     toastr.warning("请填写单位联系人手机号码！！");
    //     return;
    // }
    var linkManEmail = $("#linkManEmailInput").val();
    // if(linkManEmail == undefined || linkManEmail == ''){
    //     toastr.warning("请填写联系人邮箱！！");
    //     return;
    // }

    var uparam = {};
    var orgparam = {};
    orgparam.orgName = orgName;
    orgparam.orgType = orgType;
    orgparam.orgAddr = orgAddr;
    orgparam.orgTel = orgTel;
    orgparam.orgEmail = orgEmail;
    orgparam.orgFax = orgFax;
    orgparam.linkMan = linkMan;
    orgparam.linkManTel = linkManTel;
    orgparam.linkManPhone = linkManPhone;
    orgparam.linkManEmail = linkManEmail;
    orgparam.orgName = orgName;
    orgparam.operType = "add";
    uparam.org = orgparam;

    var result = client.callAsJson("userService/saveOrUpdateOrg", uparam);
    if(result.success){
        $("#unitAddModal").modal("hide");
        initOrg();
        toastr.info("操作成功！");
    }else{
        toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
    }
}

function _initOrgType(){
    var client = new com.im.common.ajax();
    var result = client.callAsJson("userService/queryOrgarizationsByCond", { "hasOrgType":'Y'});
    if(result.success){
        orgTypes = result.result;
        $("#selectOrgType").append("<option value=''>全部</option>");
        $("#orgTypeSel").append("<option value=''>请选择</option>");
        $.each(orgTypes,function(i,obj){
            $("#selectOrgType").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
            $("#orgTypeSel").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
        });
    }else{
        toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
    }
    $('#orgTypeSel').select2();
};

function downloadFile(path,realName){
    location.href="/FileManageWeb/fileController/downloadFile?fileName="+path+"&realName="+encodeURI(encodeURI(realName));
}

$(function() {
    var param ={};
    param.limitTypeId ="60";
    param.chkType ="2";
    param.rangeValue = '10011002';
    var staffLimitRst= com.im.staffLimitCommpent.invoke.staffLimitJudge(param);

    if (staffLimitRst != false ) {
        if (!staffLimitRst.result.ret) {
            $("#batchTrial").hide();
        } else {
            ;
        }
    }

	com.im.contractSign.invoke.init();
});
